#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "../../Include/manager/log_manager.h"
#include "../../Include/constant/knn_info.h"
#include "../../Include/domain/knn_dataset.h"

/**
 * 读取文件
 * @param path
 * @param mode
 */
struct KnnDataset ReadFile(char *path, char *mode) {
    Info("读取文件");

    FILE *file = fopen(path, mode);
    int i;
    double (*fileContent)[KNN_FILE_COLUMN_SIZE] = (double *)malloc(KNN_FILE_ROW_SIZE * KNN_FILE_COLUMN_SIZE * sizeof(double));
    char *fileLabel[KNN_FILE_ROW_SIZE];
    for (i = 0; i < KNN_FILE_ROW_SIZE; i++) {
        char buffer[KNN_FILE_COLUMN_SIZE * KNN_FILE_CELL_SIZE];
        char *row = (char *)malloc(KNN_FILE_COLUMN_SIZE * KNN_FILE_CELL_SIZE * sizeof(char));
        fgets(buffer, KNN_FILE_COLUMN_SIZE * KNN_FILE_CELL_SIZE, file);
        strcpy(row, buffer);
        // 第一行为标题，略过
        if (i == 0) {
            continue;
        } else {
            char *cell = (char *)malloc(KNN_FILE_CELL_SIZE * sizeof(char));//[KNN_FILE_CELL_SIZE];
            for (int j = 0, k = 0, l = 0; j < strlen(row); ++j) {
                // char_util.c中有split方法
                if (row[j] == ','){
                    *(*(fileContent + i - 1) + l) = atof(cell);
                    cell = (char *)malloc(KNN_FILE_CELL_SIZE * sizeof(char));
                    k = 0;
                    l++;
                    continue;
                } else if (row[j] == '\n') {
                    fileLabel[i - 1] = malloc(KNN_FILE_CELL_SIZE * sizeof(char));
                    strcpy(fileLabel[i - 1], cell);
                }else{
                    *(cell + k) = row[j];
                    k++;
                }
            }
        }
    }
    fclose(file);

    struct KnnDataset knnDataset;
    knnDataset.allDataset = fileContent;
    knnDataset.allDatasetLabel = fileLabel;
    return knnDataset;
}